/**
 * 该类：{@link ServiceDispatcher}暂时完成
 * 作用：主要进行socket的分派
 */
package com.jr.javachat.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ServiceDispatcher
 * 
 * 编写时间：2011-5-9下午08:23:18
 * @author <a href="http://xiulin.tk/">彭修林</a>
 * 
 */
public class ServiceDispatcher implements Runnable {

	private Socket userSocket;
	private ServerSocket serverSocket;
	private Server server;

	/**
	 * 构造器
	 * @param serverSocket
	 * @param server 
	 */
	public ServiceDispatcher(ServerSocket serverSocket, Server server) {
		this.serverSocket = serverSocket;
		this.server = server;
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		//分派器运行以后，监听连接用户，有用户连接以后，就将userSocket传给UserService为用户提供服务
		while(true){
			try {
				Thread.sleep(100);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				userSocket = serverSocket.accept();//一般在这里进行等待用户连接的时间最长
				//用户连接以后，立即启动一个userservice线程，为用户提供服务，然后这里执行下一次循环
				NewUserService userService = new NewUserService(userSocket,server);
				Thread t = new Thread(userService);
				t.start();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e){
				e.printStackTrace();
				System.err.println("未知错误");
				break;
			}
			
		}
	}

}
